/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package io.iec.edp.caf.multicontext.resolver;

import io.iec.edp.caf.multicontext.classloader.ModuleClassloader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * //todo 这个好像可以去掉 现在模块类加载器就是只能加载本模块资源的
 * 默认ResourceResolver 只获取本模块内资源 防止通过类加载器加载到父类资源
 *
 * @author guowenchang
 */
public class MultiContextResourceResolver extends PathMatchingResourcePatternResolver {

    public MultiContextResourceResolver(ResourceLoader resourceLoader) {
        super(resourceLoader);
    }

    protected Set<Resource> doFindAllClassPathResources(String path) throws IOException {
        Set<Resource> result = new LinkedHashSet<>(16);
        ClassLoader cl = getClassLoader();

        Enumeration<URL> resourceUrls;

        //todo 因为现在moduleContext的resouceload只有module本身的，所以getModuleResources和getResources获取的是一样的，所以和这个类可以不用了
        if (cl != null && cl instanceof ModuleClassloader) {
            resourceUrls = ((ModuleClassloader) cl).getModuleResources(path);
        } else {
            resourceUrls = (cl != null ? cl.getResources(path) : ClassLoader.getSystemResources(path));
        }

        while (resourceUrls.hasMoreElements()) {
            URL url = resourceUrls.nextElement();
            result.add(convertClassLoaderURL(url));
        }
        if (!StringUtils.hasLength(path)) {
            // The above result is likely to be incomplete, i.e. only containing file system references.
            // We need to have pointers to each of the jar files on the classpath as well...
            addAllClassLoaderJarRoots(cl, result);
        }
        return result;
    }
}
